package networkmodule;

import android.util.Log;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

import junit.framework.Assert;
import networkmodule.message.BaseNetworkMessage;
 
public class TCPClient {
    private String _serverIp = "";
    private int _serverPort;
    
    private INetworkMessageListener mMessageListener = null;
    private boolean mRun = false;
 
    PrintWriter out;
    BufferedReader in;
 
    /**
     *  Constructor of the class. OnMessagedReceived listens for the messages received from server
     */
    public TCPClient(String ip, int port, INetworkMessageListener listener) {
        mMessageListener = listener;
        _serverIp = ip;
        _serverPort = port;
    }
 
    /**
     * Sends the message entered by client to the server
     * @param message text entered by client
     */
    public void sendMessage(BaseNetworkMessage netMsg){
    	Assert.assertNotNull(netMsg);
    	String message = netMsg.serialize();
        if (out != null && !out.checkError()) {
            out.println(message);
            out.flush();
        }
    }
 
    public void stopClient(){
        mRun = false;
    }
 
    public void run() {
 
        mRun = true;
 
        try {
            //here you must put your computer's IP address.
            InetAddress serverAddr = InetAddress.getByName(_serverIp);
 
            Log.e("TCP Client", "C: Connecting...");
 
            //create a socket to make the connection with the server
            Socket socket = new Socket(serverAddr, _serverPort);
 
            try {
                //send the message to the server
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                //receive the message which the server sends back
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                
                //sendMessage("Hello Server");
                //in this while the client listens for the messages sent by the server
                int msgLength = 0;
                while (mRun) {
                	String message;
                	try {
                		 message = in.readLine();
                	} catch(IOException ex)
                	{
                		break;
                	}
                    
                	if (message != null && mMessageListener != null) {
                        //call the method messageReceived from ServerBoard class
                		mMessageListener.messageReceived(message);
                    }
 
                }
 
                Log.e("RESPONSE FROM SERVER", "S: Received Message Length: '" + msgLength + "'");
 
            } catch (Exception e) {
                Log.e("TCP", "S: Error", e);
 
            } finally {
                //the socket must be closed. It is not possible to reconnect to this socket
                // after it is closed, which means a new socket instance has to be created.
            	mRun = false;
                socket.close();
            }
 
        } catch (Exception e) {
 
            Log.e("TCP", "C: Error", e);
 
        }
 
    }
 
    //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
    //class at on asynckTask doInBackground
    public interface INetworkMessageListener {
        public void messageReceived(String message);
    }
}